// +----------------------------------------------------------------------
// | SparkShop 坚持做优秀的商城系统
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2099 http://sparkshop.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( https://opensource.org/licenses/mit-license.php )
// +----------------------------------------------------------------------
// | Author: NickBai
// +----------------------------------------------------------------------

import {
	LOGIN_TOKEN,
	UID,
	USER_INFO
} from '../../config/cache';
import Cache from '../../utils/cache';

const state = {
	token: Cache.get(LOGIN_TOKEN) || false,
	userInfo: Cache.get(USER_INFO) || {},
	uid: Cache.get(UID) || 0,
	cartCount: 0 // 购物车数量
};

const mutations = {
	LOGIN(state, opt) {
		// 确保token存在
		if (!opt || !opt.token) {
			return;
		}
		
		state.token = opt.token;
		// 使用默认过期时间60天，如果没有提供
		let expireTime = opt.time || 86400 * 60;
		Cache.set(LOGIN_TOKEN, opt.token, expireTime);
	},
	SET_UID(state, val) {
		state.uid = val;
		Cache.set(UID, val);
	},
	UPDATE_LOGIN(state, token) {
		state.token = token;
	},
	LOGOUT(state) {
		state.token = false;
		state.uid = 0
		Cache.clear(LOGIN_TOKEN);
		Cache.clear(USER_INFO);
		Cache.clear(UID);
	},
	UPDATE_USERINFO(state, userInfo) {
		state.userInfo = userInfo;
		Cache.set(USER_INFO, userInfo);
	},
	UPDATE_CART_COUNT(state, count) {
		state.cartCount = count;
	}
};

const actions = {
	login({ commit }, res) {
		return new Promise((resolve, reject) => {
			// 处理不同的数据结构，确保token能正确存储
			let data = res.data || res;
			let token = data.token || data.access_token || '';
			
			// 确保有token值
			if (!token) {
				reject(new Error('登录成功但未获取到token'));
				return;
			}
			
			// 构造标准数据结构
			let loginData = {
				token: token,
				time: data.time || data.expires_in || 7200 // 默认2小时
			};
			
			// 提取用户信息
			let userInfo = data.userInfo || data.user || {};
			if (userInfo && Object.keys(userInfo).length === 0 && data.id) {
				userInfo = { id: data.id };
			}
			
			// 提取用户ID
			let uid = userInfo.id || data.uid || data.user_id || 0;
			
			// 提交mutations
			commit('LOGIN', loginData);
			if (Object.keys(userInfo).length > 0) {
				commit('UPDATE_USERINFO', userInfo);
			}
			if (uid > 0) {
				commit('SET_UID', uid);
			}
			
			resolve();
		})
	},
};

export default {
	namespaced: true, // 启用命名空间
	state,
	mutations,
	actions
};
